package com.ltu.ai.sparkdesk.websocket.legal;

import java.net.URI;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.K;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.ltu.ai.sparkdesk.websocket.AiContextManager;
import com.ltu.ai.sparkdesk.websocket.ultra.ResponSparkData.RoleContent;
import com.ltu.domain.mp_entity.customize.SessionRecordEntity;
import com.ltu.enums.SysDict;

import lombok.extern.slf4j.Slf4j;



@Slf4j
public class LegalSocketClient extends WebSocketClient { 
	
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss.SSS");
 	private static final String TTS_HOST = "tts-api.xfyun.cn/v2/tts";
 	private static final String HostUrl = "https://";
 	private static final String  MsgTips= "想要得到更加全面专业的解答，您可以微信扫描上方小程序二维码，我们将尽快与您联系。";
    private  AiContextManager.IatContext iatContext;
    private  AiContextManager aiContextManager;
    // 开始时间
    private  Date dateBegin = new Date();
    // 结束时间
    private  Date dateEnd = null;
    //本次会话完整的回答
    private String  respContext = "";
    
    /**
     * @param serverUri
     * @param aiContextManager
     * @param iatContext
     */
    public LegalSocketClient(URI serverUri,AiContextManager aiContextManager,AiContextManager.IatContext iatContext, Map<String,String> headers ) {
//    	  super(serverUri);
    	super(serverUri,headers);
    	  this.iatContext = iatContext;
    	  this.aiContextManager = aiContextManager;
        if(serverUri.toString().contains("wss"))
            trustAllHosts(this);
        
    }
    
    public static String getCurrentTimeStr() {
        return sdf.format(new Date());
    }
    
    @Override
    public void onOpen(ServerHandshake handshake) {
        System.out.println(getCurrentTimeStr() + "\t星火Legal 律法模型Websocket连接建立成功！");
        try {
            JSONObject requestJson=new JSONObject();
            JSONObject header=new JSONObject();  // header参数
            header.put("action","chat");
            header.put("biz","");
            JSONObject payload=new JSONObject(); // payload参数
            payload.put("text", iatContext.getLegalQuestion());
            requestJson.put("header",header);
            requestJson.put("payload",payload);
            String body = requestJson.toString();
              System.err.println(body); // 可以打印看每次的传参明细
              this.send(body);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

     
//  @Override
//  public void onMessage(ByteBuffer bytes) {
//      try {
//          System.out.println(getCurrentTimeStr() + "\t服务端返回：" + new String(bytes.array(), "UTF-8"));
//      } catch (UnsupportedEncodingException e) {
//          e.printStackTrace();
//      }
//  }

    @Override
    public void onMessage(String text) {
    	log.info("AI响应结果：{}",text);
    	Gson  gson = new Gson();
    	ResponLegalData resp = gson.fromJson(text, ResponLegalData.class);
    	if(resp.getHeader().getCode()!=0) {
    		log.error("AI响应出错：{}",text);
    		return;
    	}
    	if(StringUtils.equals(resp.getHeader().getAction(), "acctBiz")) {
    		log.info("建立Legal法律模型链接成功：{}",text);
    		return;
    	}
//    	if(!StringUtils.equals(resp.getHeader().getAction(), "chat")) {
//    		log.info("非正面回答的内容：{}",text);
//    		return;
//    	}
    	//再将相应的数据发送给客户端 .get("text")
    	if( resp.getPayload().getContent()==null || (!resp.getPayload().getContent().containsKey("text") && !resp.getPayload().getContent().containsKey("questions") ))
    			return;
    	   RoleContent  rc  = null; 
    	   String respMsg = "";
    	if(StringUtils.equals(resp.getHeader().getAction(), "chat")) {
    		respMsg = resp.getPayload().getContent().getString("text");
            rc = new RoleContent(SysDict.SessionRole.ChatAI.getName(),respMsg,resp.getHeader().getAction());
    	}else if(StringUtils.equals(resp.getHeader().getAction(), "relQuestion")) {
    		JSONArray  questions = resp.getPayload().getContent().getJSONArray("questions");
            rc = new RoleContent(SysDict.SessionRole.ChatAI.getName(),questions,resp.getHeader().getAction());
            rc.setContent("");
    	}
         
    	 this.respContext =  this.respContext+respMsg;
    	//如果 ResponSparkData.header.status == 2 说明返回结束了数据存到数据，且加入历史
    	 if(resp.getHeader().getStatus() == 2 &&  StringUtils.equals(resp.getHeader().getAction(), "chat")) {
    		 
              dateEnd = new Date();
              log.info(sdf.format(dateBegin) + "开始");
              log.info(sdf.format(dateEnd) + "结束");
              log.info("耗时:" + (dateEnd.getTime() - dateBegin.getTime()) + "ms");
              log.info("最终完整答案 ==》" + respContext);
       
            SessionRecordEntity record = new SessionRecordEntity();
          	record.setDeviceMac(iatContext.getDeviceMac() )
          		  .setContent(respContext)
          		  .setRole(rc.getRole())
          		  .setCreateTime(new Date())
          		  .setSessionId(Integer.parseInt(iatContext.getSessionEntity().getId()))
          		  .setBubbleId(respMsg);
          	iatContext.getSessionEntity().setTotalQuestion( iatContext.getSessionEntity().getTotalQuestion()+1);
        	try {
        		JSONObject  jsonRC = (JSONObject) JSONObject.toJSON(rc);
               String	authUrl = AiContextManager.getAuthUrl(HostUrl + TTS_HOST).replace("http://", "ws://").replace("https://", "wss://");
               jsonRC.put("authUrl",authUrl);
               
               if(iatContext.getSessionEntity().getTotalQuestion() == 1) { 
            	    String wxQrCode = aiContextManager.getCurSessionQRCode(iatContext.getSessionEntity());
            	    jsonRC.put("wxQrCode", wxQrCode);
            	    jsonRC.put("content", rc.getContent()+"	" + MsgTips);
            	    
               }         
        	   log.info("输送设备号：{},结果：{}",iatContext.getDeviceMac(),jsonRC.toString());
               aiContextManager.responClient( iatContext.getDeviceMac(),jsonRC);
               aiContextManager.saveSessionRecord(record,iatContext.getSessionEntity());
               this.respContext ="";
			} catch (Exception e) {

				e.printStackTrace();
			}
        	
           } else {
               // todo 根据返回的数据处理
        	   log.info("输送设备号：{},结果：{}",iatContext.getDeviceMac(),JSONObject.toJSONString(rc));
        	   aiContextManager.responClient( iatContext.getDeviceMac(),rc);
			}
    		
    }

    @Override
    public void onError(Exception e) {
        System.out.println(getCurrentTimeStr() + "\t连接发生错误：" + e.getMessage() + ", " + new Date());
//        iatContext.setLegalSocketClient(null);
        e.printStackTrace();
    }

    @Override
    public void onClose(int arg0, String arg1, boolean arg2) {
        System.out.println(getCurrentTimeStr() + "\t 星火Legal 律法模型链接关闭");
        iatContext.setLegalQuestion("");
//        iatContext.setLegalSocketClient(null);
    }


    public void trustAllHosts(LegalSocketClient appClient) {
        System.out.println("wss");
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[]{};
            }

            @Override
            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                // TODO Auto-generated method stub
            }

            @Override
            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                // TODO Auto-generated method stub
            }
        }
      };

        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            appClient.setSocket(sc.getSocketFactory().createSocket());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
}